<template>
  <div id="app">
    <UserDetail id="1" a="xxx" b="yyy" hash="zzz"></UserDetail>

    <div class="todo-container">
      <div class="todo-wrap">
        <todo-header></todo-header>
        <todo-list :list="list"></todo-list>
        <todo-footer :list="list"></todo-footer>
      </div>
    </div>
  </div>
</template>

<script>
  import header from "./components/todo-header"
  import list from "./components/todo-list"
  import footer from "./components/todo-footer"
  import UserDetail from "./components/UserDetail"
  export default {
    name: 'App',
    data(){
      return {
        //待办任务对应的数组
        list:[]
      }
    },
    methods:{
      //新增一个待办任务
      addTask(task){this.list.unshift(task)},
      //删除指定任务
      detTask(id){
        this.list = this.list.filter(task=>task.id !== id)
      },
      //修改指定任务的选中状态
      updateChecked(id,checked){
         this.list = this.list.map( task =>{
           if(task.id === id){
             task.checked = checked
           }
           return task
         })
      },
      //清空已完成任务
      clearTask(){
        this.list = this.list.filter( task => task.checked===false )
      },
      //全选&全不选
      checkAllOrNone(checked){
        this.list.forEach((item)=>{
          item.checked=checked
        })
      }
    },
    components:{
      "todo-header":header,
      "todo-list":list,
      "todo-footer":footer
    },
    mounted(){
      //从浏览器的本地存储中读取 list数据;如果数据为null 则给默认值[]
      let list = localStorage.getItem("list");
      this.list = list ? JSON.parse(list) : []

      //新增一个待办任务
      this.$bus.$on("addTask",this.addTask)
      //删除指定任务
      this.$bus.$on("detTask",this.detTask)
      //修改指定任务的选中状态
      this.$bus.$on("updateChecked",this.updateChecked)
      //清空已完成任务
      this.$bus.$on("clearTask",this.clearTask)
      //全选&全不选
      this.$bus.$on("checkAllOrNone",this.checkAllOrNone)
    },
    watch:{
      list:{
        handler(newVal){
          //将修改之后的list 更新到localStorage中
          localStorage.setItem("list",JSON.stringify(newVal))
        },
        deep:true
      }
    }
  }
</script>

<style scoped>
  .todo-container {
    width: 600px;
    margin: 0 auto;
  }
  .todo-container .todo-wrap {
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 5px;
  }
</style>
